library(estimatr) 
library(ggplot2)
library(dplyr)
library(dotwhisker)
library(gridExtra)
library(coefplot)
library(tidyverse)


# Figure 7: Scenario Changes and Respondent Free Response Justifications (US Sample)


setwd("/Users/dmin/Dropbox/Replication_Data/Paper_1/")

COMdat <- read.csv("Paper_1_Data_Clean_tidy.csv", stringsAsFactors = FALSE)


gg_df<-
  COMdat %>% 
  group_by(Nationality) %>% 
  summarize(tidy(lm_robust(cbind(SupportAlly, PunishRevenge, EliminateThreat, AvoidNuclearUse, AvoidEntanglement) ~ Nuclear + Japan +Tripwire +Retaliation, data = cur_data()
                           )
                 ))

gg_df <-
  gg_df %>%
  filter(term != "(Intercept)",
         Nationality == 1) %>%
  mutate(term_label =
           factor(
             term,
             levels = c("Nuclear",
                        "Tripwire",
                        "Retaliation",
                        "Japan"),
             labels = c(
               "DPRK Attack Uses\nNuclear Weapons",
               "US Military Casualties",
               "DPRK Threat of Retaliation",
               "Target is Japan"
             )
           ),
         outcome_label = factor(outcome, levels = c("SupportAlly", "PunishRevenge", "EliminateThreat", "AvoidNuclearUse", "AvoidEntanglement"),
                                    labels = c("Support Ally", "Punishment/Revenge", "Eliminate Threat", "Avoid Nuclear Use", "Avoid Entanglement"))
  )

label_df <- 
  gg_df %>% 
  filter(term_label == "DPRK Attack Uses\nNuclear Weapons")

g <-
  ggplot(data = gg_df,
         aes(estimate, term_label, color = outcome_label, group = outcome_label, shape = outcome_label)) +
  geom_point(position = position_dodgev(height = 0.5)) +
  geom_linerange(aes(xmin = conf.low, xmax = conf.high), position = position_dodgev(height = 0.5)) +
  geom_text(data = label_df, aes(label = outcome_label, x = conf.high + 0.025), position = position_dodgev(height = 0.5)) +
  geom_vline(xintercept=0, linetype="dotted")+
  theme_bw() +
  theme(
    plot.title = element_text(face = "bold", size = 12),
    legend.position = "none",
    # legend.background = element_rect(colour="grey80"),
    axis.title.y = element_blank()
  ) +
  scale_color_manual(values = c("indianred2","forestgreen", "steelblue2", "orange", "magenta")) +
  labs(x = "Average Treatment Effect Estimate") +
  scale_y_discrete(limits=rev)+
  coord_cartesian(xlim=c(-0.15,.15))
g


ggsave("Image_7.png", plot=g, width=3500, height=1900, units=c("px"))

